import time
from abc import ABC, abstractmethod
import requests

from login import models
from tools.myjwt import mjwt


# 抽象工厂
class SflLogin(ABC):
    @abstractmethod
    def geturl(self):
        pass

    @abstractmethod
    def callback(self):
        pass


class Dingding(SflLogin):

    def geturl(self):
        from urllib.parse import quote
        params = [
            f"redirect_uri={quote('http://127.0.0.1:5173/huidiao/')}",
            "response_type=code",
            "client_id=dinges8uezk9e6kedgkq",
            "scope=openid",
            "prompt=consent",
        ]
        url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        return url

    def callback(self, code):
        authcode = code
        data = {
            "clientId": "dinges8uezk9e6kedgkq",
            "clientSecret": "fxyWuZu_F5iC6qFki97WBI1agF6u7VvnUOJM5aqxgBGujhTH6vYe0B5EGwclA0bl",
            "code": authcode,
            "grantType": "authorization_code"
        }

        resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        accessToken = resp.get('accessToken')

        # 根据accessToken获取用户信息
        headers = {"x-acs-dingtalk-access-token": accessToken}
        resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()

        name = resp.get('nick')
        uid = resp.get('openId')
        moile = resp.get('mobile')
        sfl = models.ThirdParty.objects.filter(uid=uid, party_type=3).first()

        if not sfl:
            user = models.Users.objects.filter(moile=moile).first()
            if not user:
                user = models.Users.objects.create(
                    username=name,
                    moile=moile,
                    password=moile,
                    img="userimg/1.jpg"
                )
            userinfo = models.ThirdParty.objects.create(
                user=user,
                party_type=3,
                uid=uid
            )
        else:
            user = sfl.user

        # 生成jwt token返回
        payload = {"username": user.username, "userid": user.id, "exp": int(time.time() + 60 * 60 * 2)}
        token = mjwt.jwt_encode(payload)
        payload["exp"] = int(time.time() + 60 * 60 * 2 * 24)
        refedshToken = mjwt.jwt_encode(payload)
        return {"token": token, "refedshToken": refedshToken, "code": 200, "userid": user.id}


class Fun():
    def create_f(self, type):
        if type == 3:
            return Dingding()


f = Fun()
